import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController  } from 'ionic-angular';
import { FormsModule } from '@angular/forms';
import { OrderComplatePage } from '../order-complate/order-complate';
import { ChioceAddressPage } from '../chioce-address/chioce-address';
import { Https } from '../../app/http.service'
/**
 * Generated class for the TihuoApplyPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-tihuo-apply',
  templateUrl: 'tihuo-apply.html',
})
export class TihuoApplyPage {
	//商品数量
	num:number = 1;
	//用户可转卖的卡的数量
	goodsAll = 1;
	Data = [];
	checkPwdUrl = new Https().Url + "act=goods&op=app_check_pay_pwd";
	detailUrl = new Https().Url + "act=goods&op=tihuoGoodsDetail";
	insertUrl = new Https().Url + "act=goods&op=inserttihuo";
	//支付密码
	pwd = [];
	active = 0;
	pcactive: any;
	goodsId:string;
	address = [];
	cardType:string
	addressId:number;
	isAddress:string;
	goodsName:string
	phone = ""
	goodsPrice:string;
	constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController) {
		this.goodsId = this.navParams.get("id");
		this.cardType = this.navParams.get("cardType");
		console.log(this.cardType)
    }

	ionViewDidEnter() {
		console.log('ionViewDidLoad TihuoApplyPage');
		fetch(this.detailUrl,{
			method: "post",
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token") + "&id=" + this.goodsId,
		}).then((response)=>{
			response.text().then((data)=>{
				if (data != ''){
					let json = JSON.parse(data).datas;
					if (json.code == '3'){
						this.alerts("错误，请重试");
					}else{
						console.log(json);
						// this.alerts("提货成功，请前往我的提货查看");
						
						this.Data = json.goodsInfo;
						this.phone = json.goodsInfo.phone;
						this.goodsName = json.goodsInfo.goods_name;
						this.address = json.address;
						this.addressId = json.address.address_id;
						if (this.address == null || json.address == '3'){
							this.isAddress = '3'
						}
						console.log()
						this.goodsAll = this.Data['goods_num'];
						this.goodsPrice = this.Data['goods_price'];
					}
				}else{
					this.alerts("网络连接错误，请重试");
				}
				

			})
		}).catch((error)=>{
			this.alerts(error);
		})
	}
	
	//数量
	quantity(int){
		this.num = int == 1 ? this.num >= this.goodsAll ? this.goodsAll:this.num+1 : this.num <= 1 ? this.num = 1 : this.num-1;   
		this.goodsPrice = (this.Data['goods_price'] * this.num).toFixed(2);
	}

	checkAll(){
		this.num = this.goodsAll;
	}
	//确认专卖


	choiceAddress(){
		this.navCtrl.push(ChioceAddressPage) 
	}
	
	confirm() {
		console.log(this.phone)
		let then = this;
		let alert = this.alertCtrl.create({
			cssClass: " password ",
			enableBackdropDismiss: false,
		});
		// 聚集各地建设爱好者
		if(this.cardType != "jd"){
			let phone = this.phone.match(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/)
			console.log(phone)
			if (phone == null){
				this.alerts("请输入正确的手机号");
				return false;
			}
		}
		alert.present();
		setTimeout(() => {
			//弹窗主体
			let passPop = document.querySelector(".password>.alert-wrapper")
			//弹窗内容
			passPop.innerHTML = '<div class="pord" ><div class="title" ><img src="./assets/imgs/xx.png"></img><span>请输入支付密码</span></div><div class="card-tihuo-phone"><span>充值手机:' + this.phone + '</span><span>充值金额:' + this.goodsPrice +'元</span></div><div class="hidden-pwd"  (keyup)="backkey(int,$event)" (keypress)="intkey(int,$event)"><input pattern="[0-9]*"  type="number" class="number"></div><div class="input" ><div class="pan" #int ><span contenteditable="true" ></span><span contenteditable="true" type="tel"></span><span contenteditable="true" type="tel"></span><span contenteditable="true" type="tel"></span><span contenteditable="true" type="tel"></span><span contenteditable="true" type="tel"></span></div><span class="remember"><a>忘记密码</a></span></div></div>'
			//获取关闭X的点击
			let close = document.querySelector(".password>.alert-wrapper>.pord>.title>img")
			//忘记密码
			let remember = document.querySelector(".password>.alert-wrapper>.pord>.input>.remember>a")
			//输入框
			let pwdInput = document.querySelector(".password>.alert-wrapper>.pord>.input>.pan")

			let pwdHiddenInput = document.querySelector(".password>.alert-wrapper>.pord>.hidden-pwd>input")
			close.addEventListener("click", () => {
				//关闭弹窗
				this.pwd.splice(0, this.pwd.length)
				console.log(this.pwd)
				this.active = 0
				alert.dismiss();
			})
			remember.addEventListener("click", () => {
				//忘记密码跳转
				console.log(remember)
			})
			pwdHiddenInput.addEventListener("keyup", (event: any) => {
				console.log(event.keyCode, 'keyCode')
				//输入密码
				if (event.keyCode == 8 && this.active != 0) {
					this.active = this.pwd.length - 1 <= 0 ? 0 : this.pwd.length - 1;
					if (this.active >= 0) {
						pwdInput.children[this.active].className = " "
						this.pwd.pop()
						if (this.pwd.length == 1) {
							this.pwd = [];
						}
					}

				}
			})
			pwdInput.addEventListener("keyup", (event: any) => {
				console.log(event.keyCode, 'keyCode')
				//输入密码
				if (event.keyCode == 8 && this.active != 0) {
					this.active = this.pwd.length - 1 <= 0 ? 0 : this.pwd.length - 1;
					if (this.active >= 0) {
						pwdInput.children[this.active].className = " "
						this.pwd.pop()
						if (this.pwd.length == 1) {
							this.pwd = [];
						}
					}

				}
			})
			pwdHiddenInput.addEventListener("textInput", (event: any) => {
				event.preventDefault();
				//输入密码
				// console.log(event.originalEvent.data.charCodeAt(),'keyCode')
				// console.log(event.data,'keyCode')
				// console.log(event.charCode,'charCode')
				// this.pwd[this.active] = String.fromCharCode(event.charCode)
				this.pwd[this.active] = event.data
				if (this.pwd.length == 6) {
					console.log(this.pwd);
					let pay = this.pwd[0] + this.pwd[1] + this.pwd[2];
					pwdInput.children[this.pwd.length - 1].className = "circle"
					fetch(this.checkPwdUrl, {
						method: "post",
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token") + "&pay=" + pay + "&pwn=" + this.pwd[3] + this.pwd[4] + this.pwd[5],
					}).then((response) => {
						response.text().then((json) => {
							if (json != '') {
								let data = JSON.parse(json).datas;
								if (data.code == '0') {
									console.log(123)
									this.pwd = [];
									//密码验证成功 then
									then.tihuo();
									alert.dismiss();
								} else {
									this.alerts("密码输入错误，请重新输入");
								}
							} else {
								this.alerts("网络连接错误，请重试");
							}
						})
					}).catch((err) => {
						this.alerts(err);
					})


				} else if (this.pwd.length < 6) {
					pwdInput.children[this.pwd.length - 1].className = "circle"
					this.active++;
					// // this.pcactive = pwdInput.children[this.pwd.length];
					// this.pcactive.focus()
				}
			})
			pwdInput.addEventListener("textInput", (event: any) => {
				event.preventDefault();
				//输入密码
				// console.log(event.originalEvent.data.charCodeAt(),'keyCode')
				// console.log(event.data,'keyCode')
				// console.log(event.charCode,'charCode')
				// this.pwd[this.active] = String.fromCharCode(event.charCode)
				this.pwd[this.active] = event.data
				if (this.pwd.length == 6) {
					console.log(this.pwd);
					let pay = this.pwd[0] + this.pwd[1] + this.pwd[2];
					pwdInput.children[this.pwd.length - 1].className = "circle"
					fetch(this.checkPwdUrl, {
						method: "post",
						headers: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token") + "&pay=" + pay + "&pwn=" + this.pwd[3] + this.pwd[4] + this.pwd[5],
					}).then((response) => {
						response.text().then((json) => {
							if (json != '') {
								let data = JSON.parse(json).datas;
								if (data.code == '0') {
									console.log(123)
									this.pwd = [];
									//密码验证成功 then
									then.tihuo();
									alert.dismiss();
								} else {
									this.alerts("密码输入错误，请重新输入");
								}
							} else {
								this.alerts("网络连接错误，请重试");
							}
						})
					}).catch((err) => {
						this.alerts(err);
					})


				} else if (this.pwd.length < 6) {
					pwdInput.children[this.pwd.length - 1].className = "circle"
					this.active++;
					this.pcactive = pwdInput.children[this.pwd.length];
					this.pcactive.focus()
				}
			})

		}, 100)

	}
	tihuo(){
		fetch(this.insertUrl, {
			method: "post",
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded'
			},
			body: "mid=" + localStorage.getItem("mid") + "&token=" + localStorage.getItem("token") + "&id=" + this.goodsId + "&num=" + this.num + "&all=" + this.goodsAll + "&address_id=" + this.addressId + "&goods_name=" + this.goodsName + "&phone=" + this.phone + "&type=" + this.cardType,
		}).then((response) => {
			response.text().then((data) => {
				if (data != '') {
					let json = JSON.parse(data).datas;
					if (json.code == '3') {
						this.alerts("错误，请重试");
					} else {
						this.alerts("提货成功，请前往我的提货查看");
						this.navCtrl.pop();
					}
				} else {
					this.alerts("网络连接错误，请重试");
				}


			})
		}).catch((error) => {
			this.alerts(error);
		})
	}
	alerts(text){
		let confirm = this.alertCtrl.create({
			title: '温馨提示',
			message: text,
			buttons: [
				{ text: '确定' },

			]
		});
		confirm.present();
	}
}
